<?php
require_once 'wd_widget.class.php';
require_once 'helpers.class.php';
require_once 'enums.php';

class wd_content_slider_widget extends wd_widget
{  
  
    private $contentDevider = '<!--contentpartdivider-->';
    
    private $additionalFieldIndex = 'category_name';
    
    private $pages = array();
    
    public function wd_content_slider_widget()
    {        
      $widgetOptions = array( 'description' => 'Pozwala na wyświetlenie wisów z podanej kategorii w postaci karuzeli.');
      
      parent::WP_Widget(false, __('WD Content slider'), $widgetOptions);  
      
      $this->isPlugin = true;   
      
      $this->pluginName = 'wd-content-slider';
    }  
    
    public function form($instance)
    {    
      $this->instance = $instance;
      
      $this->printStyle('wd-content-slider-admin');      
      
      $this->printInput('Title', 'title');    
     
      
      $categoryNameJs = 'jQuery("#' . $this->get_field_id('categoryName') . '")';
      
      $fieldNameJs = 'jQuery("#' . $this->get_field_id('fieldName') . '")';
      
      $hideJs = '.hide();';
      
      $showJs = '.show();';          
     
      $options = array( 
                        'Dynamic'           =>  new option(WidgetMode::DYNAMIC, $categoryNameJs.$showJs.$fieldNameJs.$showJs),
                        'Self'              =>  new option(WidgetMode::IT_SELF, $categoryNameJs.$hideJs.$fieldNameJs.$hideJs),
                        'Children'          =>  new option(WidgetMode::CHILD_PAGES, $categoryNameJs.$hideJs.$fieldNameJs.$hideJs),
                        'Field dependent'   =>  new option(WidgetMode::FIELD_DEPENDENT, $categoryNameJs.$hideJs.$fieldNameJs.$showJs),
                        'Constant category' =>  new option(WidgetMode::CONSTANT_CATEGORY, $categoryNameJs.$showJs.$fieldNameJs.$hideJs)
                      );
      
      $this->printChoice('Mode', 'mode',  $options);
      
      
      $input = new input($this->get_field_name('categoryName'), $this->get_field_id('categoryName'));
    
      $input->label = 'Category';

      $input->value = (empty($this->instance['categoryName']) ? null : esc_attr($this->instance['categoryName']));

      $input->display();      

      
      $input = new input($this->get_field_name('fieldName'), $this->get_field_id('fieldName'));
    
      $input->label = 'Field';

      $input->value = (empty($this->instance['fieldName']) ? null : esc_attr($this->instance['fieldName']));

      $input->display();
    }
    
    public function widget($args, $instance)
    {                 
      $this->preparePages($instance);
      
      $pages = $this->getPages();
      
      $this->display($pages, $instance['title']);
    }  
    
    private function pushPagesFromChildren($pageID)
    {      
      $params = array('post_type' => 'page', 'post_parent'=>$pageID);
      
      $this->pages = array_merge($this->pages, helpers::getPagesFromParams($params));
    }
    
    private function pushPagesFromItSelf($pageID)
    {      
      $currentPost = get_post($pageID);

      // tutaj jest obrazek, ale treść trzeba wywalić 
      unset($currentPost->post_content);
     
      array_push($this->pages, $currentPost);
    }
    
    
    private function pushPagesFromCategory($categoryName)
    {
      $params = array('category_name'=>$categoryName);
      
      $this->pages = array_merge($this->pages, helpers::getPagesFromParams($params));
      
      $this->pushPagesFromMedia($categoryName);
    }
    
    private function pushPagesFromMedia($categoryName)
    {
      global $wpdb;

      $query = "
        SELECT  $wpdb->posts.* 
        FROM    $wpdb->posts, $wpdb->terms, $wpdb->term_relationships
        WHERE   $wpdb->posts.id = $wpdb->term_relationships.object_id
        AND     $wpdb->term_relationships.term_taxonomy_id = $wpdb->terms.term_id
        AND     $wpdb->terms.name = '$categoryName'
        AND     $wpdb->posts.post_type = 'attachment'
      ";

      $pages = $wpdb->get_results($query, OBJECT);

      $this->pages = array_merge($this->pages, $pages);
    }

    private function getPages()
    {   
      if(!empty ($this->pages))
      {        
        $outPages = array();

        foreach($this->pages as $inPage)
        {           
          $outPage = new stdClass();
          
          // jezeli trafilismy na media to podmianka bo adres do obrazka jest zawarty w guid
          if($inPage->post_type == 'attachment')
          {
            $outPage->image = $inPage->guid;            
          }
          else
          {
            $image = wp_get_attachment_image_src( get_post_thumbnail_id( $inPage->ID ), 'single-post-thumbnail' );  
            $outPage->image = $image[0];
          }
          
          $contentPart = explode($this->contentDevider, $inPage->post_content);
          
          $outPage->text = $contentPart[0];
          
          $outPage->title = $inPage->post_title;
          
          $outPage->permalink = (count($contentPart) < 3 ? '#' : get_permalink($inPage->ID));   
          
          array_push($outPages, $outPage);          
        }       
        
        return $outPages;        
      }
      
      return null;
    }
    
    private function preparePages($args)
    {
        $mode = $args['mode'];      
      
        $categoryName = null;
        
        $pageID = helpers::getPageId();  
      
        if($mode == WidgetMode::CONSTANT_CATEGORY || $mode == WidgetMode::DYNAMIC)
        {         
          $categoryName = $args['categoryName'];
          
          if($categoryName != '' && !is_null($categoryName))
          {
            $this->pushPagesFromCategory($categoryName);
          }          
        }   
        
        if($mode == WidgetMode::FIELD_DEPENDENT || $mode == WidgetMode::DYNAMIC)
        {           
          $categoryName = get_post_meta($pageID, $args['fieldName'], true);    
          
          if($categoryName != '' && !is_null($categoryName))
          {
            $this->pushPagesFromCategory($categoryName);
          }          
        }        
        
        if($mode == WidgetMode::CHILD_PAGES || $mode == WidgetMode::DYNAMIC)
        {          
          $this->pushPagesFromChildren($pageID);          
        }
        
        if($mode == WidgetMode::IT_SELF || $mode == WidgetMode::DYNAMIC)
        {
          $this->pushPagesFromItSelf($pageID);
        }            
    }

    public function display($pages, $title = null)
    {      
      if($pages != null)
      {             
        if($title != null)
        {
          $title = sprintf('<h3 class="widget-title">%s</h3>', $title);
        }
        
        $nullContentWrapper = '<div class="slide-wrapper" %s"></div>';

        $contentWrapper = '<div class="slide-wrapper" %s>
                            <div class="content-wrapper">
                              <a class="title" href="%s">%s</a>
                              <div class="content">%s</div>
                              <a class="meta-nav" href="%s"></a>
                            </div>
                          </div>';
        
          
        if(count($pages) > 1)
        {           
          $this->printStyle('wd-content-slider');

          wp_enqueue_script("jquery");  
          wp_print_scripts('jquery');

          $this->printScript('loopedslider.min', 'jquery');
          $this->printScript('wd-content-slider', 'jquery');
        }

        $i = 0;
        
        $content = null;
        
        foreach($pages as $page)
        {            
          // jezeli jest tresc albo chociaz załączone zdjęcie 
          if($page->text != '' || !is_null($page->image))
          {            
            // TODO: dobrze opisać bo będzie rzeżnia!
            if($i < 2 || $i >= count($pages) - 2)
            {
              $image = 'style="background-image: url(' . $page->image . ');"';
            }
            else
            {
              $image = 'img="'. $page->image .'"';
            }            
            
            // jezeli nie ma treści co bierzemy tylko załaczony obrazek
            if(is_null($page->text) || $page->text == '')
            {
              $content .=  sprintf($nullContentWrapper, $image);
            }
            else
            {              
              $content .= sprintf($contentWrapper,  $image, $page->permalink, $page->title, $page->text, $page->permalink); 
            }   
            
            $i++;             
          }           
        }      
        
      // upewniamy się że mamy co wyświetlić  
      if(!is_null($content) && !empty ($content))
      {        
        $list = sprintf(' <div class="widget-content" id="wd-content-slider">
                            <div class="container">
                              <div class="slides">%s</div>
                            </div>
                            <div class="pagination-container"><a class="previous" href="#"></a> <a class="next" href="#"></a></div>
                          </div>', $content); 
        
        $this->getWidget($title.$list);        
      }      
    }    
  }    
}  
?>